package com.bestcem.xm.ticket.controller.convert;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.bestcem.xm.ticket.controller.param.ticket.template.TemplateParam;
import com.bestcem.xm.ticket.controller.param.ticket.template.UpdateTemplateParam;
import com.bestcem.xm.ticket.controller.vo.template.GetRecentTemplateVO;
import com.bestcem.xm.ticket.controller.vo.ticket.template.GetTemplateInfoVO;
import com.bestcem.xm.ticket.entity.mongo.TicketTemplate;
import com.bestcem.xm.ticket.entity.mongo.TicketTemplateV2;
import com.bestcem.xm.ticket.enums.TemplateFieldTypeEnum;
import com.bestcem.xm.ticket.enums.TemplateSelectSourceEnum;
import com.bestcem.xm.ticket.enums.TemplateTypeEnum;
import com.bestcem.xm.ticket.enums.TicketTemplateFieldUpdatedEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import java.util.*;

/**
 * 模板的转换类
 *
 * @author xuan.yang <xuan.yang@idiaoyan.com>
 * @version v1.0
 * @date 2021/9/6 17:14
 */
@Slf4j
public class TemplateConvert {

    /**
     * UpdateTemplateParam.FieldInfo to TicketTemplateV2.FieldInfo
     *
     * @param fieldInfos 字段列表
     * @return 转换后的字段列表
     * @author ympan <yuming.pan@idiaoyan.com>
     * @date 22:58 2021/9/9
     */
    public static List<TicketTemplateV2.FieldInfo> fieldInfoConvertForUpd(List<UpdateTemplateParam.FieldInfo> fieldInfos) {
        List<TicketTemplateV2.FieldInfo> list = new ArrayList<>();
        if (CollUtil.isEmpty(fieldInfos)) {
            return list;
        }
        for (UpdateTemplateParam.FieldInfo sourceInfo : fieldInfos) {
            TicketTemplateV2.FieldInfo targetInfo = new TicketTemplateV2.FieldInfo();
            targetInfo.setName(sourceInfo.getName());
            targetInfo.setType(sourceInfo.getType());
            targetInfo.setRequired(sourceInfo.getRequired());
            targetInfo.setField(sourceInfo.getField());
            // setSingleSelect的处理
            if (TemplateFieldTypeEnum.SELECT.getIndex().equals(sourceInfo.getType())) {
                TicketTemplateV2.SingleSelect singleSelect = new TicketTemplateV2.SingleSelect();
                singleSelect.setSource(sourceInfo.getSingleSelect().getSource());
                List<TicketTemplateV2.SingleSelect.Option> optionList = new ArrayList<>();
                List<UpdateTemplateParam.SingleSelect.Option> singleSelectOptionList = sourceInfo.getSingleSelect().getOptionList();
                // 非自定义数据会导致singleSelectOptionList为null，但为null是可以接受的，所以需要在此做处理
                if (Objects.isNull(singleSelectOptionList)) {
                    singleSelectOptionList = new ArrayList<>();
                }
                for (UpdateTemplateParam.SingleSelect.Option sourceOption : singleSelectOptionList) {
                    TicketTemplateV2.SingleSelect.Option targetOption = new TicketTemplateV2.SingleSelect.Option();
                    targetOption.setField(sourceOption.getField());
                    targetOption.setValue(sourceOption.getValue());
                    optionList.add(targetOption);
                }
                singleSelect.setOptionList(optionList);
                targetInfo.setSingleSelect(singleSelect);
            }
            // setCascadeList的处理
            if (TemplateFieldTypeEnum.CASCADE_SELECT.getIndex().equals(sourceInfo.getType())) {
                List<TicketTemplateV2.Cascade> cascadeList = new ArrayList<>();
                for (UpdateTemplateParam.Cascade sourceCascade : sourceInfo.getCascadeList()) {
                    TicketTemplateV2.Cascade targetCascade = new TicketTemplateV2.Cascade();
                    targetCascade.setLevel(sourceCascade.getLevel());
                    List<TicketTemplateV2.Option> cascadeOptionList = new ArrayList<>();
                    for (UpdateTemplateParam.Cascade.Option sourceOption : sourceCascade.getOptionList()) {
                        TicketTemplateV2.Option targetOption = new TicketTemplateV2.Option();
                        targetOption.setId(sourceOption.getId());
                        targetOption.setPid(sourceOption.getPid());
                        targetOption.setValue(sourceOption.getValue());
                        cascadeOptionList.add(targetOption);
                    }
                    targetCascade.setOptionList(cascadeOptionList);
                    cascadeList.add(targetCascade);
                }
                targetInfo.setCascadeList(cascadeList);
            }
            list.add(targetInfo);
        }
        return list;
    }

    /**
     * TemplateParam.FieldInfo to TicketTemplateV2.FieldInfo
     *
     * @param fieldInfos 字段列表
     * @return 转换后的字段列表
     * @author ympan <yuming.pan@idiaoyan.com>
     * @date 23:04 2021/9/9
     */
    public static List<TicketTemplateV2.FieldInfo> fieldInfoConvertForInsert(List<TemplateParam.FieldInfo> fieldInfos) {
        List<TicketTemplateV2.FieldInfo> list = new ArrayList<>();
        if (CollUtil.isEmpty(fieldInfos)) {
            return list;
        }
        for (TemplateParam.FieldInfo sourceInfo : fieldInfos) {
            TicketTemplateV2.FieldInfo targetInfo = new TicketTemplateV2.FieldInfo();
            // 如果字段名称是处理记录，设置他的update不可以修改

            if (StringUtils.equals("处理记录", sourceInfo.getName())) {
                targetInfo.setIsUpdate(TicketTemplateFieldUpdatedEnum.TEMPLATE_NOT_UPDATE.getIndex());
            }
            targetInfo.setName(sourceInfo.getName());
            targetInfo.setType(sourceInfo.getType());
            targetInfo.setRequired(sourceInfo.getRequired());
            targetInfo.setField(sourceInfo.getField());
            // setSingleSelect的处理
            if (TemplateFieldTypeEnum.SELECT.getIndex().equals(sourceInfo.getType())) {
                TicketTemplateV2.SingleSelect singleSelect = new TicketTemplateV2.SingleSelect();
                singleSelect.setContent(sourceInfo.getSingleSelect().getContent());
                singleSelect.setSource(sourceInfo.getSingleSelect().getSource());
                List<TicketTemplateV2.SingleSelect.Option> optionList = new ArrayList<>();
                List<TemplateParam.SingleSelect.Option> sourceOptionList = sourceInfo.getSingleSelect().getOptionList();
                if (CollectionUtil.isNotEmpty(sourceOptionList)) {
                    for (TemplateParam.SingleSelect.Option sourceOption : sourceOptionList) {
                        TicketTemplateV2.SingleSelect.Option targetOption = new TicketTemplateV2.SingleSelect.Option();
                        targetOption.setField(sourceOption.getField());
                        targetOption.setValue(sourceOption.getValue());
                        optionList.add(targetOption);
                    }
                }
                singleSelect.setOptionList(optionList);
                targetInfo.setSingleSelect(singleSelect);
            }
            // setCascadeList的处理
            if (TemplateFieldTypeEnum.CASCADE_SELECT.getIndex().equals(sourceInfo.getType())) {
                List<TicketTemplateV2.Cascade> cascadeList = new ArrayList<>();
                for (TemplateParam.Cascade sourceCascade : sourceInfo.getCascadeList()) {
                    TicketTemplateV2.Cascade targetCascade = new TicketTemplateV2.Cascade();
                    targetCascade.setLevel(sourceCascade.getLevel());
                    List<TicketTemplateV2.Option> cascadeOptionList = new ArrayList<>();
                    for (TemplateParam.Option sourceOption : sourceCascade.getOptionList()) {
                        TicketTemplateV2.Option targetOption = new TicketTemplateV2.Option();
                        targetOption.setId(sourceOption.getId());
                        targetOption.setPid(sourceOption.getPid());
                        targetOption.setValue(sourceOption.getValue());
                        cascadeOptionList.add(targetOption);
                    }
                    targetCascade.setOptionList(cascadeOptionList);
                    cascadeList.add(targetCascade);
                }
                targetInfo.setCascadeList(cascadeList);
            }
            list.add(targetInfo);
        }
        return list;
    }


    /**
     * 数据库获得的模板详情转换为包装的详情返回
     *
     * @param sourceInfoList 字段列表
     * @return 转换后的字段列表
     * @author xuan.yang
     * @date 11:18 2021/9/13
     */
    public static List<GetTemplateInfoVO.FieldInfo> fieldInfoConvertForGet(List<TicketTemplateV2.FieldInfo> sourceInfoList) {
        if (CollUtil.isEmpty(sourceInfoList)) {
            return Collections.emptyList();
        }
        List<GetTemplateInfoVO.FieldInfo> targetInfoList = new ArrayList<>();
        for (TicketTemplateV2.FieldInfo sourceInfo : sourceInfoList) {
            GetTemplateInfoVO.FieldInfo targetInfo = new GetTemplateInfoVO.FieldInfo();
            targetInfo.setName(sourceInfo.getName());
            targetInfo.setType(sourceInfo.getType());
            targetInfo.setRequired(sourceInfo.getRequired());
            targetInfo.setField(sourceInfo.getField());
            // setSingleSelect的处理
            if (TemplateFieldTypeEnum.SELECT.getIndex().equals(sourceInfo.getType())) {
                GetTemplateInfoVO.SingleSelect singleSelect = new GetTemplateInfoVO.SingleSelect();
                if (!Objects.isNull(sourceInfo.getSingleSelect())) {
                    singleSelect.setContent(sourceInfo.getSingleSelect().getContent());
                    singleSelect.setSource(sourceInfo.getSingleSelect().getSource());
                    List<GetTemplateInfoVO.SingleSelect.Option> optionList = new ArrayList<>();
                    //如果自定义选项来源
                    if (TemplateSelectSourceEnum.CUSTOMER_SOURCE.getIndex().equals(singleSelect.getSource())) {
                        sourceInfo.getSingleSelect().getOptionList().forEach(option ->
                                optionList.add(new GetTemplateInfoVO.SingleSelect.Option(option.getField(), option.getValue()))
                        );
                    }
                    singleSelect.setOptionList(optionList);
                    targetInfo.setSingleSelect(singleSelect);
                }

            } else if (TemplateFieldTypeEnum.CASCADE_SELECT.getIndex().equals(sourceInfo.getType())) {
                List<GetTemplateInfoVO.Cascade> cascadeList = new ArrayList<>();
                for (TicketTemplateV2.Cascade cascade : sourceInfo.getCascadeList()) {
                    GetTemplateInfoVO.Cascade targetCascade = new GetTemplateInfoVO.Cascade();
                    targetCascade.setLevel(cascade.getLevel());
                    List<GetTemplateInfoVO.Option> targetOptions = new ArrayList<>();
                    // 循环添加级联
                    cascade.getOptionList().forEach(option ->
                            targetOptions.add(new GetTemplateInfoVO.Option(option.getId(), option.getPid(), option.getValue()))
                    );
                    targetCascade.setOptionList(targetOptions);
                    cascadeList.add(targetCascade);
                }
                targetInfo.setCascadeList(cascadeList);
            }
            targetInfoList.add(targetInfo);
        }
        return targetInfoList;


    }

    public static TicketTemplateV2 convertOldTemplateToTemplateV2(TicketTemplate ticketTemplate) {
        TicketTemplateV2 templateV2 = new TicketTemplateV2();
        templateV2.setId(ticketTemplate.getId());
        templateV2.setOrgId(ticketTemplate.getOrgId());
        templateV2.setCreatedId(ticketTemplate.getCreatedId());
        templateV2.setCreatedDate(ticketTemplate.getCreatedDate());
        templateV2.setUpdatedDate(ticketTemplate.getUpdatedDate());
        templateV2.setUpdatedId(ticketTemplate.getUpdatedId());
        templateV2.setTicketConfigId(ticketTemplate.getTicketConfigId());
        List<TicketTemplate.FieldInfo> customFields = ticketTemplate.getCustomFields();
        List<TicketTemplate.FieldInfo> defaultFields = ticketTemplate.getDefaultFields();

        List<TicketTemplateV2.FieldInfo> infoList = new LinkedList<>();
        // 老数据添加默认字段 处理记录
        TicketTemplateV2.FieldInfo fieldInfo = new TicketTemplateV2.FieldInfo();
        fieldInfo.setField("field0");
        fieldInfo.setName("处理记录");
        fieldInfo.setRequired(true);
        fieldInfo.setType(2);
        infoList.add(0, fieldInfo);


        if (CollUtil.isNotEmpty(defaultFields)) {
            infoList.addAll(convert(defaultFields));
        }
        if (CollUtil.isNotEmpty(customFields)) {
            infoList.addAll(convert(customFields));
        }

        templateV2.setFieldList(infoList);
        return templateV2;
    }

    /**
     * 这里实现真正的拼接逻辑
     *
     * @param fieldInfos
     * @return
     */
    @Nonnull
    private static List<TicketTemplateV2.FieldInfo> convert(List<TicketTemplate.FieldInfo> fieldInfos) {
        List<TicketTemplateV2.FieldInfo> newFieldInfoList = new ArrayList<>();
        if (CollUtil.isEmpty(fieldInfos)) {
            return new ArrayList<>();
        }
        fieldInfos.forEach(fieldInfo -> {
            TicketTemplateV2.FieldInfo newFieldInfo = new TicketTemplateV2.FieldInfo();
            TemplateFieldTypeEnum typeEnum = TemplateFieldTypeEnum.getByName(fieldInfo.getType());
            if (Objects.isNull(typeEnum)) {
                log.info("---------fieldInfo不合法{}----", fieldInfo);
                return;
            }
            newFieldInfo.setField(fieldInfo.getField());
            newFieldInfo.setType(typeEnum.getIndex());

            boolean flag = false;
            if (Boolean.TRUE.equals(fieldInfo.getRequired()) || Integer.valueOf(1).equals(fieldInfo.getRequired())) {
                flag = true;
            }
            newFieldInfo.setRequired(flag);
            newFieldInfo.setName(fieldInfo.getText());
            // 单选需要额外处理
            if (StrUtil.equals(fieldInfo.getType(), TemplateFieldTypeEnum.SELECT.getName())) {
                List<TicketTemplate.FieldInfo.Option> options = fieldInfo.getOptions();
                TicketTemplateV2.SingleSelect select = new TicketTemplateV2.SingleSelect();
                select.setSource(1);
                List<TicketTemplateV2.SingleSelect.Option> optionList = new ArrayList<>();
                if (CollUtil.isNotEmpty(options)) {

                    options.forEach(option ->
                            optionList.add(new TicketTemplateV2.SingleSelect.Option(option.getText(), option.getValue()))
                    );
                }
                select.setOptionList(optionList);
                newFieldInfo.setSingleSelect(select);
            }
            newFieldInfoList.add(newFieldInfo);
        });
        // 排个序，按照isupdate从小到大排
        return newFieldInfoList;

    }

    public static GetRecentTemplateVO convertToTemplateRecentVO(List<TicketTemplateV2> templateV2List) {
        if (CollUtil.isEmpty(templateV2List)) {
            return null;
        }
        GetRecentTemplateVO templateVO = new GetRecentTemplateVO();
        // 封装属性返回
        templateV2List.forEach(templateV2 -> {
            if (TemplateTypeEnum.TEMPLATE_INFO.getIndex().equals(templateV2.getType())) {
                templateVO.setDetailName(templateV2.getName());
                templateVO.setDetailId(templateV2.getId());
            } else if (TemplateTypeEnum.TEMPLATE_HANDLE.getIndex().equals(templateV2.getType())) {
                templateVO.setHandleName(templateV2.getName());
                templateVO.setHandleId(templateV2.getId());
            } else {
                if (log.isInfoEnabled()) {
                    log.info("----------详情模板类型有误{}-------", templateV2);
                }
            }
        });
        return templateVO;

    }

}
